import React, { useState, useEffect } from 'react';
import { Card, message, Spin, Result, Button } from 'antd';
import { useParams, useNavigate } from 'react-router-dom';
import { questionService } from '@/services/questionService';
import { Question } from '@/types/question';
import { QuestionForm } from '@/pages/share/question';
import styles from './Practice.module.css';

const QuestionPractice: React.FC = () => {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [score, setScore] = useState<number | null>(null);
  const [correctCount, setCorrectCount] = useState(0);
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();

  // 获取题目详情
  useEffect(() => {
    const fetchQuestion = async () => {
      if (!id) return;
      
      try {
        setLoading(true);
        // 如果是练习模式，这里可以获取多个题目，或者修改后端API支持批量获取
        const response = await questionService.getQuestion(Number(id));
        if (response.data?.code === 200) {
          const questionData = response.data.data as Question;
          setQuestions([questionData]);
        }
      } catch (error) {
        message.error('获取题目失败');
      } finally {
        setLoading(false);
      }
    };

    fetchQuestion();
  }, [id]);

  // 提交答案
  const handleSubmit = async (values: any) => {
    try {
      setSubmitting(true);
      
      // 转换表单数据为后端需要的格式
      let successCount = 0;
      
      // 逐题提交答案
      for (const [key, value] of Object.entries(values)) {
        const questionId = Number(key.replace('question_', ''));
        try {
          // 提交答案到后端 API
          const response = await questionService.submitAnswer({
            question: questionId,
            answer: value
          });
          
          if (response.data?.code === 200) {
            const result = response.data.data;
            if (result.is_correct) {
              successCount++;
            }
          }
        } catch (error) {
          console.error(`提交题目 ${questionId} 答案失败`, error);
        }
      }
      
      // 计算得分
      const calculatedScore = Math.round((successCount / questions.length) * 100);
      setCorrectCount(successCount);
      setScore(calculatedScore);
      message.success('提交成功');
      setSubmitted(true);
    } catch (error) {
      message.error('提交失败');
    } finally {
      setSubmitting(false);
    }
  };

  // 返回列表
  const handleBackToList = () => {
    navigate('/question');
  };

  // 重新做题
  const handleRedo = () => {
    setSubmitted(false);
    setScore(null);
    setCorrectCount(0);
  };

  // 渲染提交后的结果
  const renderResult = () => {
    return (
      <Result
        status={score && score >= 60 ? 'success' : 'warning'}
        title={`您的得分：${score || 0}分`}
        subTitle={`共 ${questions.length} 题，答对 ${correctCount} 题${score && score >= 60 ? '，恭喜通过测试！' : '，继续努力，再接再厉！'}`}
        extra={[
          <Button key="back" onClick={handleBackToList}>
            返回题库
          </Button>,
          <Button key="redo" type="primary" onClick={handleRedo}>
            重新做题
          </Button>,
        ]}
      />
    );
  };

  return (
    <Card title="题目练习" className={styles.card}>
      <Spin spinning={loading}>
        {questions.length > 0 ? (
          submitted ? (
            renderResult()
          ) : (
            <QuestionForm
              questions={questions}
              onFinish={handleSubmit}
              loading={submitting}
              submitButtonText="提交答案"
            />
          )
        ) : (
          <div className={styles.empty}>加载题目中...</div>
        )}
      </Spin>
    </Card>
  );
};

export default QuestionPractice; 